from django.conf import settings
from django.shortcuts import redirect
import re

class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.required_urls = [re.compile(url) for url in settings.LOGIN_REQUIRED_URLS]
        self.excepted_urls = [re.compile(url) for url in settings.LOGIN_REQUIRED_URLS_EXCEPTIONS]

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        # 检查是否需要登录
        path = request.path_info
        
        # 检查是否在例外列表中
        if any(url.match(path) for url in self.excepted_urls):
            return None
            
        # 检查是否在需要登录的URL列表中
        if any(url.match(path) for url in self.required_urls):
            # 如果用户未登录，重定向到登录页面
            if not request.user.is_authenticated:
                return redirect(settings.LOGIN_URL)
        
        return None
